package com.nhic.blog.web.admin;

import com.nhic.blog.po.User;
import com.nhic.blog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/admin")
public class LoginController {

    @Autowired
    private UserService userService;

    @GetMapping
    public String loginPage(Model model) {
        System.out.println("hahahha ");
        model.addAttribute("urlName", "登录");
        return "admin/login";
    }

    @PostMapping("/login")
    public String login(@RequestParam String username,
                        @RequestParam String password,
                        HttpSession session,
                        RedirectAttributes attributes) {
        User user = userService.checkUser(username, password);
        if (user != null) {
            user.setPassword(null);
            session.setAttribute("user", user);
            return "redirect:/admin/index";
        } else {
            return "redirect:/admin";
        }
    }

    @GetMapping("/index")
    public String adminIndex() {
        return "admin/index";
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("user");
        return "redirect:/admin";
    }

    @GetMapping("/updatePage")
    public String updatePage() {
        return "admin/updatePassword";
    }

    @PostMapping("/updatePassword")
    public String updatePage(User user,Model model,RedirectAttributes attributes) {
        /*重定向传参可以使用RedirectAttributes，使用model无法传参数*/
        User user1 = userService.checkUser(user.getUsername(),user.getPassword());
        if (user1 == null) {
            model.addAttribute("notexit", "您的用户或旧密码错误");
            return null;
        } else {
            userService.updatePwd(user);
            attributes.addFlashAttribute("tip","跟新成功！");
            return "redirect:/admin";
        }
    }
}
